import { Space, Button, message, Typography, Descriptions, Modal, } from 'antd';
import ProCard from '@ant-design/pro-card';
import React, { useState, useRef, useEffect } from 'react';
import { getDvaApp, history, } from 'umi';
import ProForm, {
    ProFormText,
    ProFormSelect,
} from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { FooterToolbar, PageContainer } from '@ant-design/pro-layout';
import $utils from '@/utils/utils';
import { CabinetCreate, CabinetUpdate, getCabinetDetail, CabinetCellSlaveList, getCabinetTariff } from '@/services/cabinet';
import { FindByAuthCode } from '@/services/imei';
import { modelTypes, brandNames, mainTypes } from '@/utils/common';


const { Title } = Typography;

const Detail: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    const formRef = useRef<ProFormInstance>();
    const actionRef = useRef<ActionType>();

    const [selectedRowKey, setSelectedRowKey] = useState<React.Key[]>([]);
    const [cur_id, setCur_id] = useState<string>();
    const [cabinetDetail, setCabinetDetail] = useState<any>();
    const [cabinetCellData, setCabinetCellData] = useState<any>([]);
    const [imeiData, setImeiData] = useState<any>();

    const [tariffNames, setTariffNames] = useState<API.Select[]>([]);

    const l_state: any = history.location.state;

    if (!cur_id && !l_state) {
        history.push('/BasicConfig/IMEI');
    }

    const id: string = l_state?.data?.id || '';
    //  同path更新,只更新state时，通过id重新请求数据
    if ((l_state && id) && (!cur_id || cur_id !== id)) {
        setCur_id(id);
    } else if (l_state && !id && cur_id !== id) {
        setCur_id('');
    }

    const isCreate: boolean = l_state?.status === 'create';
    const isUpdate: boolean = l_state?.status === 'update';
    const isDetail: boolean = l_state?.status === 'detail';

    useEffect(() => {

        // 获取柜体详情
        const getCabinetDetails = async () => {
            try {
                const msg = await getCabinetDetail({ id: cur_id });;
                if (msg.code === 0) {
                    const detail = (msg.body);
                    detail.fullName = `${detail.regionInfo.provinceName}/${detail.regionInfo.cityName}/${detail.regionInfo.countyName}`;
                    detail.regionInfo_name = detail.regionInfo.townName;
                    setCabinetDetail(detail);
                    formRef && formRef.current?.resetFields();
                    return;
                }
            } catch (error) {
                console.log(error);
            }
        };
        // 获取副柜列表
        const getCabinetCellSlaveList = async () => {
            try {
                const msg = await CabinetCellSlaveList({ cabId: cur_id });;
                if (msg.code === 0) {
                    setCabinetCellData(msg.body);
                    actionRef && (actionRef?.current?.reload());
                    return;
                }
            } catch (error) {
                console.log(error);
            }
        };

        if (l_state?.cabDetail && l_state?.cellData) {
            setCabinetDetail(l_state?.cabDetail);
            setCabinetCellData(l_state?.cellData);

            formRef && formRef.current?.resetFields();
            actionRef && (actionRef?.current?.reload());
        } else if (!cur_id) {
            setCabinetDetail(undefined);
            setCabinetCellData([getNewCabinet()]);

            formRef && formRef.current?.resetFields();
            actionRef && (actionRef?.current?.reload());
        }
        else {
            getCabinetDetails();
            getCabinetCellSlaveList();
        }
    }, [cur_id]);

    useEffect(() => {
        const getCabinetTariffData = async () => {
            const userInfo = $utils.getStorage('user_info');
            try {
                const msg = await getCabinetTariff({ stationId: userInfo.stationId });
                let new_data: API.Select[] = [];
                if (msg.code === 0) {
                    msg.body.map((item: { id: number, name: string }) => {
                        new_data.push({
                            label: item.name,
                            value: item.id,
                        });
                    });
                    formRef && formRef.current?.setFieldValue('tariffpkgId', new_data[0].value);
                    setTariffNames(new_data);
                    return;
                }
            } catch (error) {
                console.log(error);
                message.error('资费套餐列表获取失败!');
            }
        };

        getCabinetTariffData();
    }, [])

    // 新增柜子默认信息
    const getNewCabinet = (index: number = 0) => {
        const allChars = $utils.getAllChars();
        let code = null, newIndex = index;
        // 创建副柜时需要去掉AI、AO
        if (newIndex >= 34) { newIndex++; }
        if (newIndex >= 40) { newIndex++; }

        if (newIndex >= allChars.length) {
            code = allChars[Math.floor(newIndex / allChars.length) - 1] + allChars[newIndex % allChars.length];
        }
        else {
            code = $utils.getAllChars()[newIndex];
        }
        return {
            code: code,
            cabId: cur_id,
            name: `${code}号柜`,
            main: 2,
            big: 0,
            bigger: 0,
            cellNum: 0,
            middle: 0,
            small: 0,
            tiny: 0,
        }
    };

    // 根据授权码获取imei信息
    const getImeiData = async (value: string) => {
        try {
            const msg = await FindByAuthCode({ authCode: value });;
            if (msg.code === 0) {
                const code = msg.body.code || cabinetDetail?.code;
                formRef?.current?.setFieldValue('code', code);
                formRef?.current?.setFieldValue('model', msg.body.model);
                formRef?.current?.setFieldValue('brand', msg.body.brand);
                setImeiData(msg.body);
                return;
            } else {
                formRef?.current?.setFieldValue('code', '');
                formRef?.current?.setFieldValue('model', '');
                formRef?.current?.setFieldValue('brand', '');
            }
        } catch (error) {
            console.log(error);
        }
    };

    // 增加一个副柜
    const addCabinet = () => {
        const newCabinet = getNewCabinet(cabinetCellData.length);
        const newData: any = [].concat(cabinetCellData);
        newData.push(newCabinet);
        setCabinetCellData(newData);
    };

    // 删除副柜
    const deleteCabinet = () => {
        const newData: any = JSON.parse(JSON.stringify(cabinetCellData));
        newData.pop();
        setCabinetCellData(newData);
    };

    const confirmDelete = () => {
        Modal.confirm({
            title: '删除',
            content: '确认删除此柜体?',
            centered: true,
            maskClosable: true,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                // 删除imei
                deleteCabinet();
            }
        });
    };

    // 设置主柜
    const setMainType = () => {
        const newData: any = JSON.parse(JSON.stringify(cabinetCellData));
        newData.map((item: any) => {
            if (item.code === selectedRowKey[0]) {
                item.main = 1;
            } else {
                item.main = 2;
            }
        });
        setCabinetCellData(newData);
        setSelectedRowKey([]);
    };

    const equipment_columns: ProColumns<any>[] = [
        {
            title: '柜体',
            dataIndex: 'name',
            width: '100px',
        },
        {
            title: '主/副柜',
            dataIndex: 'main',
            width: '100px',
            valueType: 'select',
            fieldProps: {
                options: mainTypes
            }
        },
        {
            title: '格口总数(个)',
            dataIndex: 'cellNum',
            width: '120px',
        },
        {
            title: '超大格口',
            dataIndex: 'bigger',
            width: '130px',

        },
        {
            title: '大格口',
            dataIndex: 'big',
            width: '120px',
        },
        {
            title: '中格口',
            dataIndex: 'middle',
            width: '120px',
        },
        {
            title: '小格口',
            dataIndex: 'small',
            width: '120px',
        },
        {
            title: '超小格口',
            dataIndex: 'tiny',
            width: '120px',
        },
        !isDetail ? {
            title: '操作',
            dataIndex: 'callbackTime',
            width: '120px',
            render: (dom, record, index) => {
                return (<div key={record.code}>
                    <Space>
                        <Button type="primary" disabled={isUpdate && cabinetDetail.status !== 2 && record.status !== 11101} onClick={() => {
                            const newTab = {
                                name: isCreate ? `设置新建柜体${record.code}号柜格口类型` : `设置柜体${cabinetDetail.code}${record.code}号柜格口类型`,
                                path: '/BasicConfig/Cabinet/cellType',
                                state: {
                                    status: l_state?.status,
                                    data: record,
                                    cabDetail: { ...cabinetDetail, ...formRef?.current?.getFieldsValue() },
                                    cellData: cabinetCellData
                                },
                            };
                            // 设置当前tab对象
                            $utils.setNewTab(dispatch, newTab);
                            $utils.addTab(dispatch, newTab)
                            history.push({
                                pathname: '/BasicConfig/Cabinet/cellType',
                                state: {
                                    status: l_state?.status,
                                    data: record,
                                    cabDetail: { ...cabinetDetail, ...formRef?.current?.getFieldsValue() },
                                    cellData: cabinetCellData,
                                    imeiData: imeiData || cabinetDetail
                                }
                            });
                        }}>设置格口类型</Button>
                        {isCreate && cabinetCellData.length - 1 === index && <Button type="primary" onClick={() => {
                            addCabinet();
                        }}>增加</Button>}
                        {isCreate && cabinetCellData.length > 1 && cabinetCellData.length - 1 === index && <Button type="primary" danger onClick={() => {
                            confirmDelete();
                        }}>删除</Button>}
                    </Space>
                </div>)
            }
        } : {},
    ];

    //  获取所有副柜格口总数
    const getCellTotal = (data: any) => {
        let result = 0;
        data.map((item: any) => {
            result = result + item.cellNum;
        });
        return result;
    };

    // 柜体数统计计算
    const mainCount = +(cabinetCellData?.findIndex((item: any) => item.main === 1) > -1);    // TODO 主柜数量
    const deputyCount = (cabinetCellData?.filter((item: any) => item.main === 2).length);
    const cellTotal = getCellTotal(cabinetCellData);

    return (
        <PageContainer>
            {((isCreate && !l_state.cabDetail) || cabinetDetail) && <ProCard style={{ marginTop: 8 }} gutter={8} >
                <Title level={3}>基础信息</Title>
                <ProForm
                    rowProps={{
                        gutter: [16, 0],
                    }}
                    layout={"horizontal"}
                    formRef={formRef}
                    grid={true}
                    initialValues={cabinetDetail ? cabinetDetail : undefined}
                    onFinish={async (values) => {
                        const isFreeCabinet = cabinetCellData.findIndex((item: any) => item.cellNum === 0);
                        const isHaveMain = cabinetCellData.findIndex((item: any) => item.main === 1);
                        if (isHaveMain < 0) {
                            return message.warning('请设置主柜');
                        } else if (isFreeCabinet > -1) {
                            return message.warning('柜体格口数不能为0 ，请核对');
                        }

                        // 编辑或新建提交的参数
                        const params: any = {
                            model: values.model,
                            authCode: values.authCode,
                            name: values.name,
                            code: values.code,
                            brand: values.brand,
                            phone: values.phone,
                            addr: values.addr,
                            tariffpkgId: values.tariffpkgId,
                            slaveCount: cabinetCellData.length,
                        }, cabSlaves: any = [];
                        cabinetCellData.map((item: any) => {
                            const data: any = {
                                cellNum: item.cellNum,
                                main: item.main,
                                code: item.code,
                            };
                            item.id && (data.id = item.id);
                            item.cellList && (data.cellList = item.cellList);
                            cabSlaves.push(data);
                        });
                        params.cabSlaves = JSON.stringify(cabSlaves);

                        if (isCreate) {
                            const msg = await CabinetCreate(params);
                            if (msg.code === 0) {
                                message.success('新增成功', 1, () => {
                                    // 设置当前tab对象
                                    $utils.setNewTab(dispatch, { name: '柜体管理', path: '/BasicConfig/Cabinet', isTopMenu: true });
                                    history.push('/BasicConfig/Cabinet');
                                });
                            }
                        }
                        else if (isUpdate) {
                            params.id = cur_id;
                            const msg = await CabinetUpdate({ ...params, id: cur_id });
                            if (msg.code === 0) {
                                message.success('编辑成功', 1, () => {
                                    // 设置当前tab对象
                                    $utils.setNewTab(dispatch, { name: '柜体管理', path: '/BasicConfig/Cabinet', isTopMenu: true });
                                    history.push('/BasicConfig/Cabinet');
                                });
                            }
                        }
                    }}
                    submitter={{
                        render: (props, doms) => {
                            return [
                                <FooterToolbar>
                                    <Space>
                                        {!isDetail && <Button type="primary" htmlType="submit">保存</Button>}
                                        <Button onClick={() => {
                                            // 设置当前tab对象
                                            $utils.setNewTab(dispatch, { name: '柜体管理', path: '/BasicConfig/Cabinet', isTopMenu: true });
                                            history.push('/BasicConfig/Cabinet');
                                        }}>取消</Button>
                                    </Space>
                                </FooterToolbar>
                            ]
                        }
                    }}
                >
                    <ProFormText
                        name="authCode"
                        label={'授权码'}
                        disabled={!isCreate}
                        rules={[
                            {
                                required: true,
                            }
                        ]}
                        validateTrigger={'onBlur'}
                        fieldProps={{
                            maxLength: 32,
                            onBlur: () => {
                                const value = formRef.current?.getFieldValue('authCode');
                                value && getImeiData(value);
                            }
                        }}
                    />
                    <ProForm.Group>
                        <ProFormText
                            colProps={{ md: 12, xl: 8 }}
                            name="code"
                            label={'柜体编号'}
                            disabled={!!imeiData?.code || !isCreate}
                            rules={[
                                {
                                    required: true,
                                },
                                {
                                    pattern: new RegExp('^[0-9]*$', 'g'),
                                    message: '请输入数字'
                                }
                            ]}
                        />
                        <ProFormSelect
                            colProps={{ md: 12, xl: 8 }}
                            name="model"
                            label={'设备型号'}
                            disabled={true}
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                            fieldProps={{
                                options: modelTypes
                            }}
                        />
                        <ProFormSelect
                            colProps={{ md: 12, xl: 8 }}
                            name="brand"
                            label={'设备品牌'}
                            disabled={true}
                            rules={[
                                {
                                    required: true,
                                }
                            ]}
                            fieldProps={{
                                showSearch: true,
                                options: brandNames,
                            }}
                        />
                        <ProFormText
                            colProps={{ md: 12, xl: 8 }}
                            name="name"
                            label={'柜体名称'}
                            disabled={isDetail}
                            fieldProps={{
                                maxLength: 30
                            }}
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                        />
                        {!isCreate && <ProFormText
                            colProps={{ md: 12, xl: 8 }}
                            name="stationName"
                            label={'驿站名称'}
                            disabled={true}
                            fieldProps={{
                                maxLength: 30
                            }}
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                        />}
                        <ProFormSelect
                            colProps={{ md: 12, xl: 8 }}
                            name="tariffpkgId"
                            label={'资费名称'}
                            disabled={isDetail}
                            fieldProps={{
                                options: tariffNames,
                                showSearch: true,
                            }}
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                        />
                        <ProFormText
                            colProps={{ md: 12, xl: 8 }}
                            name="phone"
                            label={'运维电话'}
                            disabled={isDetail}
                            fieldProps={{
                                maxLength: 11,
                            }}
                            rules={[
                                {
                                    required: true,
                                },
                                {
                                    min: 7,
                                },
                            ]}
                        />
                        {isDetail && <ProFormText
                            colProps={{ md: 12, xl: 8 }}
                            disabled={isDetail}
                            name="fullName"
                            label={'所属地区'}
                            rules={[
                                {
                                    required: true,
                                }
                            ]}
                        />}
                        {isDetail && <ProFormText
                            colProps={{ md: 12, xl: 8 }}
                            disabled={isDetail}
                            name="regionInfo_name"
                            label={'所属街道'}
                            rules={[
                                {
                                    required: true,
                                }
                            ]}
                        />}
                        <ProFormText
                            colProps={{ md: 12, xl: 8 }}
                            name="addr"
                            label={'短信地址'}
                            disabled={isDetail}
                            fieldProps={{
                                maxLength: 25
                            }}
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                        />
                    </ProForm.Group>
                    <ProForm.Group>

                    </ProForm.Group>
                    <Title level={3}>设备规格</Title>
                    <ProForm.Group>
                        {isCreate ? <Button type="primary" disabled={selectedRowKey.length === 0} onClick={() => {
                            setMainType();
                        }}>设置为主柜</Button>
                            : <Descriptions title="" column={12} labelStyle={{ color: '#999' }}>
                                <Descriptions.Item span={1} label="主柜">{mainCount}</Descriptions.Item>
                                <Descriptions.Item span={1} label="副柜">{deputyCount}</Descriptions.Item>
                                <Descriptions.Item span={2} label="格口总数">{cellTotal}</Descriptions.Item>
                                <Descriptions.Item span={2} label=""> </Descriptions.Item>
                                <Descriptions.Item span={2} label=""> </Descriptions.Item>
                                <Descriptions.Item span={2} label=""> </Descriptions.Item>
                            </Descriptions>}
                    </ProForm.Group>
                    <ProTable
                        rowKey="code"
                        actionRef={actionRef}
                        search={false}
                        pagination={false}
                        toolBarRender={false}
                        columns={equipment_columns}
                        dataSource={cabinetCellData}
                        tableAlertRender={false}
                        rowSelection={isCreate ? {
                            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                            // 注释该行则默认不显示下拉选项
                            type: 'radio',
                            selectedRowKeys: selectedRowKey,
                            defaultSelectedRowKeys: [],
                            onChange: (newSelectedRowKeys: React.Key[]) => {
                                setSelectedRowKey(newSelectedRowKeys);
                            }
                        } : false}
                    />
                </ProForm>
            </ProCard>}
        </PageContainer>
    );
};

export default Detail;
